import React, { Component } from 'react';
import {renderToString} from 'react-dom/server'
import { WeaAlertPage, WeaLocaleProvider, WeaMap } from 'ecCom';
import { observer } from 'mobx-react';
import { toJS } from 'mobx';
import MapUtil from '../../util/mapUtil';
import isEmpty from 'lodash/isEmpty';

const getLabel = WeaLocaleProvider.getLabel;
const createDetailTemplete = (c, isGoogleMap = false) => {
  const { crm = [], pics = [] } = c;
  let picDom = '', crmDom = '';
  pics.map(pic => picDom += `<div class='mb5-img'><img src=${pic} border="0" width="65" height="64"/></div>`);
  crm.map(d => crmDom += `<div class='crm-text-elli'>${d}</div>`);

  return `<div class="hrm-map-detail ${isGoogleMap ? 'isGoogle' : ''}">
            <i class="cursor-pointer icon-coms-Clear" onclick='return closeHrmMapInfoWindow();'></i>
            <div class="mb5">
              <span class="mr10">${c.name}</span>
              <span class="gray mb5">${c.time}</span>
              <span class="signTitle">${c.signTitle}</span>
            </div>
            <div class='info-wrap'>
              ${c.information ? `<div class="mb5 m-information">${c.information}</div>` : ''}
              ${c.pics ? `<div class="mb5">${picDom}</div>` : ''}
              ${crm && crm.length > 0 ?
              `
              <div class='mb5' style="display: flex">
                <i class="icon-coms-currency-Customer" style="margin-right: 10px; color: #999;font-size:14.3px"></i>
                <div style="flex: 1, width: '98%'">
                ${crmDom}
                </div>
              </div>
              ` : ''}
              <div class="gray" style="display: flex">
                <i class="icon-coms-position" style="margin-right: 10px; color: #999; font-size:13.3px"></i>
                <div class='location'>
                ${c.title}
                </div> 
              </div>
            </div>
          </div>`;
}

@observer
export default class MapView extends Component {
    componentDidMount() {
      window.closeHrmMapInfoWindow = this.closeInfoWindow;
      const { newOutSide } = this.props;
      const { getData, init } = newOutSide;
      newOutSide.redraw = this.draw;
      getData();
    }

    setMapRef = ref => {
      if(ref && this.mapUtil == null){
        this.mapUtil = new MapUtil(ref);
      }
    }

    amapEvents = { 
      created: instance => {
        this.mapUtil.mapInstance = instance;
        this.draw();
      }
    }
  
    initEndCallback = () => {
      this.draw();
      // const {isAmap, isGoogleMap} = this.mapUtil;
      // console.debug(isAmap, isGoogleMap)
    }

    closeInfoWindow = () => {
      this.mapUtil && this.mapUtil.closeInfoWindow();
    }

    draw = () => {
      if(!this.mapUtil)
        return;
      const {newOutSide} = this.props;
      const mapDatas = toJS(newOutSide.mapData);
      const {isAmap, isGoogleMap, clearMapData, addMarker, addPolyline, setFitView} = this.mapUtil;
      //清理地图数据
      clearMapData();
      //自适应数据
      const boundDatas = [];
      const polylinePath = [];
      let idx = 1;
      //添加marker
      mapDatas.map((d, i) => {
        d.items.reverse().map((d, i) => {
          const {x: longitude, y: latitude} = d || {};
          if(longitude && latitude){
            const otherParams = {};
            isAmap && Object.assign(otherParams, {
              offset: new window.AMap.Pixel(-17, -34), 
              title: d.title, 
              content: `<div class='markerContent markerRBg'>${idx}</div>`,
              events: [
                {
                  event: 'click',
                  onEventHandle: e => {
                    const data = {marker: e.target, content: createDetailTemplete(d), isCustom: true};
                    this.mapUtil.openInfoWindow(data);
                  }
                }
              ]
            });
            isGoogleMap && Object.assign(otherParams, {
              events: [
                {
                  event: 'click',
                  onEventHandle: () => {
                    const data = {content: createDetailTemplete(d, true), isCustom: true};
                    this.mapUtil.openInfoWindow(data, {
                      position: {lat: Number(latitude), lng: Number(longitude)}
                    });
                  }
                }
              ]
            })
            isGoogleMap && Object.assign(otherParams, {label:{text:String(i + 1), color:'#fff'}});
            const marker = addMarker({latitude, longitude}, null, null, otherParams);
            isAmap && boundDatas.push(marker) && polylinePath.push([longitude, latitude]);
            isGoogleMap && boundDatas.push({latitude, longitude}) && polylinePath.push({lat: Number(latitude), lng: Number(longitude)});
            idx++;
          }
        })
      })
      //添加polyline
      polylinePath.length > 0 && addPolyline(polylinePath);
      //地图元素自适应
      setFitView(boundDatas);
    }

    render(){
      const {newOutSide} = this.props;
      const mapDatas = toJS(newOutSide.mapData);

      if(isEmpty(mapDatas)){
        return (
          <div className="grayBG" >
            <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@ufbfbw`} icon={<img style={{ width: 77, height: 97 }} src="/cloudstore/resource/pc/com/images/no_sign.png" />}>
              <div>{getLabel('386505', '当天无外勤签到记录')}</div>
            </WeaAlertPage>
          </div>
        );
      }else{
        const mapProps = { zoom: 14, onMapSwitch: type => {}, events: this.amapEvents, initGoogleEndCallback: this.initEndCallback};
        return (
          <div style={{ height: 'calc(100% - 150px)'}}>
            <div className="wea-hrm-map" style={{ width: '100%', height: '100%' }}>
              <WeaMap ecId={`${this && this.props && this.props.ecId || ''}_WeaMap@p8rhlp`} {...mapProps} ref={ref => this.setMapRef(ref)}/>
            </div>
          </div>
        )
      }
    }
}
